package com.cj.servcie.impl;

import com.cj.dao.EmployeeDao;
import com.cj.dao.impl.EmployeeDaoImpl;
import com.cj.entity.Employee;
import com.cj.servcie.EmployeeService;
import com.cj.utils.PageBean;

import java.sql.Connection;
import java.util.List;

/**
 * Employee员工信息业务层
 */
public class EmployeeServiceImpl implements EmployeeService {

    //导入Employee员工的持久层
    private EmployeeDao empDao = new EmployeeDaoImpl();


    //员工列表信息
    @Override
    public List<Employee> empList() {
        return empDao.empList();
    }

    /**
     * 添加员工信息
     *
     * @param emp
     */
    @Override
    public int addEmployee(Employee emp) {
        int result = empDao.addEmployee(emp);
        if (result == 0) {
            throw new RuntimeException("添加员工信息失败！");
        }
        return result;
    }

    /**
     * 修改员工信息
     *
     * @param emp
     */
    @Override
    public int updateEmployee(Employee emp) {
        int result = empDao.updateEmployee(emp);
        if (result == 0) {
            throw new RuntimeException("修改员工信息失败！");
        }
        return result;
    }

    /**
     * 根据id删除员工信息
     *
     * @param id
     */
    @Override
    public int deleteEmployee(int id) {
        int result = empDao.deleteEmployee(id);
        if (result == 0) {
            throw new RuntimeException("删除员工信息失败！");
        }
        return result;
    }

    @Override
    public Employee getEmployeeById(int id) {
        return empDao.getEmployeeById(id);
    }

    @Override
    public void closeConn() {
        empDao.closeConn();
    }

    @Override
    public PageBean<Employee> empListBypage(int page) {
        PageBean<Employee> pageBean = new PageBean<>();

        // 设置当前页数
        pageBean.setPage(page);

        // 设置每页显示记录数
        int limit = 8;
        pageBean.setLimit(limit);

        // 调用Dao层的方法查询总记录数
        int totalCount = empDao.empList().size();
        pageBean.setTotalCount(totalCount);

        // 设置总页数
        int totalPage;
        if (totalCount % limit == 0)
            totalPage = totalCount / limit;
        else
            totalPage = totalCount / limit + 1;
        pageBean.setTotalPage(totalPage);

        // 查询结果集的起始位置可以推倒公式为(page - 1) * limit
        int begin = (page - 1) * limit;
        List<Employee> list = empDao.empListBypage(begin, limit);
        pageBean.setList(list);
        return pageBean;
    }


}
